<template>
  <div class="newLogin">
    <p class="icon font_family icon-a-zu110 btn" @click="closeWindow"></p>
    <div class="login_title">
      <span>登录</span>
      <img src="../assets/image/login_title.png">
    </div>
    <form class="login_form">
      <input type="text" v-model="user" class="login_user">
      <input type="password" v-model="password" class="login_password">
      <div class="codeBox">
        <input type="text" v-model="picText">
        <img :src="imgSrc" @click="setGuid">
      </div>
      <div class="login_forgot">
        <img src="../assets/image/login_point.png" @click="jumpToBottom">
        <span>忘记密码，请联系管理员</span>
      </div>
      <div @click="loginSubmit" :class="{ 'login_btn': true, 'active': isFormComplete }">用户登录</div>
    </form>
  </div>
</template>

<script>
import indexHead from '../components/indexhead'
import comFoot from '../components/comfoot'
// import {mapActions} from 'vuex'
import Victor from './../assets/js/vector'
import $ from 'jquery'

export default {
  data() {
    return {
      user: '',
      password: '',
      imgSrc: '',
      picText: '',
      uuID: '',
      isFormComplete: false
    }
  },
  created() {
    document.addEventListener('click', this.onClickOutside);
  },
  components: {
    comFoot,
    indexHead
  },
  props: {
    closeWindow: {
        type: Function,
        required: true
    }
  },
  mounted() {
    // var ipv6 = "";
    // var old_token = localStorage.getItem('TOKEN_KEY')
    // if(old_token==null){
    //   old_token = "1"
    // }
    // let self = this;
    // $.getJSON("https://v4v6.ipv6-test.com/json/widgetdata.php?callback=?", function(result){
    //   if(result.proto=="ipv6"){
    //     ipv6 = result.address;
    //   }
    //   self.$axios.request({
    //     url: "5000/oauth/get/token",
    //     method: "post",
    //     headers: {
    //       'Content-Type': 'application/x-www-form-urlencoded',
    //     },
    //     params: {
    //       access_token: old_token,
    //     }
    //   }).then(res => {
    //     let token = res.data.access_token
    //     if (old_token!=null && token == old_token ) {
    //       localStorage.setItem('TOKEN_KEY', token)
    //       self.$router.push('/index')
    //       window.location.reload();
    //     }
    //     self.$axios
    //     .request({
    //       url: "5000/authentication/ipfree",
    //       method: "post",
    //       headers: {
    //           'Content-Type': 'application/x-www-form-urlencoded',
    //           'client-id': 'webApp',
    //           'client-secret': 'webApp',
    //         },
    //       params: {
    //           ipv6: ipv6,
    //         }
    //     })
    //     .then(res => {
    //         let old_token = localStorage.getItem('TOKEN_KEY')
    //         let token = res.data.access_token
    //         if (token!=null && old_token == token) {
    //           localStorage.setItem('TOKEN_KEY', token)
    //           self.$router.push('/index')
    //           window.location.reload();
    //         }

    //     })
    //     .catch((error)=>{
    //       if (error.response.status === 401  && error.response.data.resp_msg==="此账号已过期") {
    //         self.$message({
    //             message: error.response.data.resp_msg,
    //             type: 'error',
    //             duration: 3000,
    //             onClose: function(){
    //               console.log('消息框已关闭');
    //             },
    //             showClose: true
    //         });
    //         let old_token = localStorage.getItem('TOKEN_KEY')
    //         if(old_token!=null){
    //           localStorage.clear()
    //           window.location.reload(); 
    //         }
    //       }
    //     }) 
    //   }).catch((error)=>{
    //     self.$axios
    //         .request({
    //           url: "5000/authentication/ipfree",
    //           method: "post",
    //           headers: {
    //               'Content-Type': 'application/x-www-form-urlencoded',
    //               'client-id': 'webApp',
    //               'client-secret': 'webApp',
    //           },
    //           params: {
    //             ipv6: ipv6,
    //           }
    //         })
    //         .then(res => {
    //             let old_token = localStorage.getItem('TOKEN_KEY')
    //             let token = res.data.access_token
    //             if (token!=null ) {
    //               localStorage.setItem('TOKEN_KEY', token)
    //               self.$router.push('/index')
    //               window.location.reload();
    //             }
    //         })
    //         .catch((error)=>{
    //           if (error.response.status === 401  && error.response.data.resp_msg==="此账号已过期") {
    //             self.$message({
    //                 message: error.response.data.resp_msg,
    //                 type: 'error',
    //                 duration: 3000,
    //                 onClose: function(){
    //                   console.log('消息框已关闭');
    //                 },
    //                 showClose: true
    //             });
    //             let old_token = localStorage.getItem('TOKEN_KEY')
    //             if(old_token!=null){
    //               localStorage.clear()
    //               window.location.reload(); 
    //             }
    //           } else if (error.response.status === 401  && error.response.data.resp_msg==="用户不存在") {
    //             let old_token = localStorage.getItem('TOKEN_KEY')
    //             if(old_token!=null){
    //               localStorage.setItem('TOKEN_KEY', 1)
    //               window.location.reload(); 
    //             }
    //           }
    //         }) 
    //   })
    // });


    // this.$axios
    //   .request({
    //     url: "5000/authentication/ipfree",
    //     method: "post",
    //     headers: {
    //         'Content-Type': 'application/x-www-form-urlencoded',
    //         'client-id': 'webApp',
    //         'client-secret': 'webApp',
    //       },
    //   })
    //   .then(res => {
    //       let old_token = localStorage.getItem('TOKEN_KEY')
    //       let token = res.data.access_token
    //       if(!old_token || old_token != token){
    //           localStorage.setItem('TOKEN_KEY', token)
    //           this.$router.push('/index')
    //           window.location.reload();
    //       }

    //     })
    //     .catch((error)=>{
    //     }) 
    this.setGuid()
    $(function () {
      // 初始化 传入dom id
      var victor = new Victor("container", "output");
      var theme = [
        ["#002c4a", "#005584"],
        ["#35ac03", "#3f4303"],
        ["#ac0908", "#cd5726"],
        ["#18bbff", "#00486b"]
      ]
    });
  },
  watch: {
    user: 'checkFormComplete',
    password: 'checkFormComplete',
    picText: 'checkFormComplete'
  },
  methods: {
    // ...mapGetters({
    //     'getUserInfo':'getUserInfo'
    // }),
    onClickOutside(event) {
      if (event.srcElement.nodeName != 'IMG') {
        document.getElementById("admin-phone").setAttribute('style', '');
      }
    },
    setGuid() {
      var that = this

      function guid() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
          var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
          return v.toString(16);
        });
      }

      this.uuID = guid()
      this.imgSrc = 'https://www.shujuquan.cn/5000/validata/code/' + this.uuID
      console.log(this.imgSrc)
      console.log('新的UUID：' + this.uuID)
    },
    jumpToBottom() {
      const pageHeight = document.documentElement.scrollHeight;
      // 设置滚动位置到页面底部
      window.scrollTo(0, pageHeight);
      document.getElementById("admin-phone").setAttribute('style', 'background-color:#ff8203;')
    },
    loginSubmit() {
      localStorage.setItem('LOGIN_TYPE', 'USERNAME')
      console.log('获取的UUID：' + this.uuID)
      const loading = this.$loading({
        lock: true,
        text: '正在登录...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.$axios.request({
        url: "5000/oauth/user/token",
        method: "post",
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'client-id': 'webApp',
          'client-secret': 'webApp',
        },
        params: {
          password: this.password,
          username: this.user,
          grant_type: 'password',
          deviceId: this.uuID,
          validCode: this.picText,
          client_id: 'webApp',
          client_secret: 'webApp',
        }
      })
        .then(res => {
          console.log(res, '------')
          let token = res.data.access_token
          localStorage.setItem('TOKEN_KEY', token)

          this.closeWindow(); // 修改为使用 this.closeWindow()
          // this.$router.push('/index')
          // window.location.reload();
        })
        .catch((error) => {
          if (error.response.status === 401 && error.response.data.resp_msg === "此账号已过期") {
            this.$message({
              message: error.response.data.resp_msg,
              type: 'error',
              duration: 3000,
              onClose: function () {
                console.log('消息框已关闭');
              },
              showClose: true
            });
          }
          let old_token = localStorage.getItem('TOKEN_KEY')
        })
        .finally(() => {
          loading.close();
        })
    },
    checkFormComplete() {
      this.isFormComplete = this.user && this.password && this.picText;
    },
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
.newLogin {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 400px;
  z-index: 100;
  background: #000;
  .btn{
    position: absolute;
    color: #7F6D6C;
    font-size: 20px;
    right: 10px;
    top: 20px;
    cursor: pointer;
  }

  .login_icon {
    width: 100%;
    display: block;
  }

  .login_title {
    color: #7F6D6C;
    font-size: 26px;
    margin-top: 20px;
    margin-bottom: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    line-height: 1;

    img {
      height: 26px;
      margin-left: 20px;
    }
  }

  .login_form {
    width: 80%;
    padding: 0;
    background: none;

    input {
      width: 100%;
      height: 34px;
      margin-bottom: 22px;
      margin-top: 0;
      padding: 0;
      background: #7F6D6C;
      padding-left: 34px;
      box-sizing: border-box;
      font-size: 20px;
    }

    .login_user {
      background: url(../assets/image/input_bg1.png) no-repeat;
      background-size: 100% 100%;
    }

    .login_password {
      background: url(../assets/image/input_bg2.png) no-repeat;
      background-size: 100% 100%;
    }

    .codeBox {
      display: flex;
      width: 100%;
      border-radius: 6px;
      overflow: hidden;

      img {
        width: 110px;
        height: 34px;
      }

      input {
        flex: 1;
        border-radius: 6px 0 0 6px;
        padding-left: 20px;
      }
    }

    .login_forgot {
      color: #7F6D6C;
      font-size: 14px;
      line-height: 20px;
      margin-top: 0;

      img {
        margin-right: 5px;
        width: 14px;
      }
    }

    .login_btn {
      width: 100%;
      height: 34px;
      background: #7F6D6C;
      color: #000;
      font-size: 16px;
      line-height: 34px;
      text-align: center;
      border-radius: 34px;
      cursor: pointer;
      font-weight: 500;
      margin-top: 14px;
      margin-bottom: 30px;

      &.active {
        background: #CB0211;
      }
    }
  }
}
</style>